﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using InterfaceXAML.Common;
using InterfaceXAML.ExaPlanningService;
using Windows.UI.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
using Windows.Media.MediaProperties;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage.FileProperties;
using Windows.Graphics.Imaging;
using Windows.Storage;
using System.Diagnostics;



// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace InterfaceXAML.ProjectPages
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class TeamProjectPage : InterfaceXAML.Common.LayoutAwarePage
    {
        private List<CollaboratorViewModel> _collabs;
        
        private ProjectFullDetailModel _project;

        public Visibility IsAuthorize { get; set; }

        public TeamProjectPage()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            var reference = e.Parameter as string;
            Init(reference);

            IsAuthorize = App.Utilisateur.JobID == (int)JobEnum.RA || App.Utilisateur.JobID == (int)JobEnum.ChefProjet ? Visibility.Visible : Visibility.Collapsed;
        }

        private async void Init(string reference)
        {
            _collabs = await App.ExaPlanningServiceClient.GetTeamProjectAsync(reference);
            _project = await App.ExaPlanningServiceClient.GetProjectAsync(reference);
            ProjectName.Text =  _project.Name;
            DataContext = new { Collabs = _collabs };
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void AjouterCollabClick(object sender, RoutedEventArgs e)
        {
            OpenBoard.Begin();
        }

        private void CollapseBoard(object sender, RoutedEventArgs e)
        {
            CloseBoard.Begin();
        }

        private async void SearchButtonClick(object sender, RoutedEventArgs e)
        {
            var collab = "";
            SearchEdit.Document.GetText(TextGetOptions.NoHidden, out collab);

            // Appel au WS et mise à jour de la liste de recherche
            SearchList.ItemsSource = await App.ExaPlanningServiceClient.GetCollaboratorsAsync(collab);
        }

        private async void DeleteCollab(object sender, RoutedEventArgs args)
        {
            var login = ((sender as Button).FindName("Login_Delete") as TextBlock).Text;
            try
            {
                await App.ExaPlanningServiceClient.RemoveCollabFromTeamProjectAsync(_project.Reference, login);
                (itemListView.ItemsSource as List<CollaboratorViewModel>).Remove(_collabs.Find(c => c.Login == login));
                DataContext = null;
                DataContext = new { Collabs = _collabs };
            }
            catch (Exception e)
            {

            }
        }

        private async void SearchEditChange(object sender, RoutedEventArgs e)
        {
            var collab = "";
            SearchEdit.Document.GetText(TextGetOptions.NoHidden, out collab);

            if (collab.Length < 3)
            {
                SearchList.ItemsSource = null;
                return;
            }
            // Appel au WS et mise à jour de la liste de recherche
            SearchList.ItemsSource = await App.ExaPlanningServiceClient.GetCollaboratorsAsync(collab);
            
        }

        private async void AddCollab(object sender, SelectionChangedEventArgs args)
        {
            if (SearchList.SelectedIndex == -1)
                return;

            var collabLogin = (SearchList.SelectedItem as CollaboratorViewModel).Login;

            try
            {
                await App.ExaPlanningServiceClient.AddCollabToTeamProjectAsync(_project.Reference, collabLogin);
                _collabs.Add(SearchList.SelectedItem as CollaboratorViewModel);
                DataContext = null;
                DataContext = new { Collabs = _collabs };
                SearchList.SelectedIndex = -1;
            }
            catch (Exception e)
            {

            }
        }
    }
}
